define(['jquery', 'bootstrap', 'backend', 'table', 'form'], function ($, undefined, Backend, Table, Form) {

    var questionsList = {}
    var questionsValue = {}
    
    var createBtnFun = {
        // 获取：课程id
        course_id:function(){
            return $('[name="row[course_id]"]').val()
        },
        // 获取：课程难度
        diffdata:function(){
            return $('[name="row[diffdata]"]:checked').val()
        },
        // 获取：创建表单的题数
        getCreateFormData:function(){
            var form = $('#create-auto-form')
            var formData = form.serialize()
            // console.log('formData: ', formData);
            formData+='&course_id='+this.course_id()
            formData+='&diffdata='+this.diffdata()
            return formData
        },
        createAutoFormIndex:null,
        createBtnFormIndex:null,
        questionTypeObj : {
            1:'单选题',
            2:'多选题',
            3:'判断题',
            4:'填空题',
            5:'问答题'
        },
        // 渲染一条问题列表
        addOneNewQuestionList:function(row,grade,ind){
            var opts = JSON.parse(row.optionjson)
            var optsKey = ['A','B','C','D','E','F','G']
            var optsLine = []
            opts.forEach((element,index) => {
                optsLine.push('<div class="opt-list">'+optsKey[index]+'.'+element.value+'</div>')
            });
            var html = `
            <div class="question-list">
                <div class="title">
                    ${ind}.${row.title}
                </div>
                <div class="opts">
                    ${optsLine.join('')}
                </div>
                
            `
            if(grade !== false){
                html+=`
                <div class="grade">
                                    分数 <input type="number" class="grades" value="${grade}">
                                    <button type="button" class="btn btn-danger remove-question">剔除</button>
                                </div>
                `
            }
            html+='</div>'
            
            return html
        },
        // 重新写入题目信息和计算总分
        updateQuestionValue:function(){
            
            $('[name="row[questions]"]').val(JSON.stringify(questionsValue))
                
            // 计算总分
            var gradeTotal = 0;

            for (const key in questionsValue) {
                if (Object.hasOwnProperty.call(questionsValue, key)) {
                    const element = questionsValue[key];                        
                    element.forEach(ele => {
                        // console.log('ele: ', ele);
                        gradeTotal += Number(ele.grade)
                    });
                }
            }
            $('[name="row[grades]"]').val(gradeTotal)
        },
        // 更新问题数量显示
        updateQuestion:function(){
            

                // 显示题目数量
                var arr = []
                for (const key in createBtnFun.questionTypeObj) {
                    if (Object.hasOwnProperty.call(createBtnFun.questionTypeObj, key)) {
                        const element = createBtnFun.questionTypeObj[key];
                        var len
                        if(typeof questionsValue['type'+key] == 'undefined'){
                            len = 0
                        }
                        else{
                            len = questionsValue['type'+key].length
                        }
                        arr.push('<span>'+element+'（'+ len +'）</span>')
                    }
                }
                $('.questions-box').html(arr.join('，'))
                // console.log('arr: ', arr);

                this.updateQuestionValue()
        },
        // 打开选择问题的窗口
        openChooseQuestionWindow:function(type){
            var url = '../questions/list'
            
            if(location.pathname.includes('/edit')){
                url = '../../../questions/list'
            }

            // http://faoj.ccc/bXxcaZzWRH.php/testpaper/edit/
            // http://faoj.ccc/bXxcaZzWRH.php/testpaper/add?dialog=1
            // 课程id 难度 题目类型
            
            var course_id = createBtnFun.course_id()
            var diffdata = createBtnFun.diffdata()
           

            url+='?typedata='+type+'&course_id='+course_id
            if(diffdata != 0){
                url+='&diffdata='+diffdata
            }
            // 弹窗显示问题列表
            layer.open({
            type: 2,//1 dom或文本，2 iframe,3 加载层,4 tips
            shadeClose:true,
            title:'请选择试题',
            area: ['100%', '100%'],
            content: url ,
            success: function(layero){
                
            }
            });
        }
    }

    // 判断是否已经选择了这道题
    window.hasQuestionYet = function(question){
        var key = 'type'+question.typedata
        var has = false;
        for (const k in questionsValue[key]) {
            if (Object.hasOwnProperty.call(questionsValue[key], k)) {
                const element = questionsValue[key][k];
                if(element.id == question.id){
                    has = true;
                    break;
                }
            }
        }
        return has
    }

    // 添加一道新题
    window.addQuestion = function(question){
        // 一道题目的信息
        console.log(question);
        var key = 'type'+question.typedata

        if(typeof questionsList[key] == 'undefined'){
            questionsList[key] = []
        }
        if(typeof questionsValue[key] == 'undefined'){
            questionsValue[key] = []
        }
        // 避免重复添加题目
        for (const k in questionsValue[key]) {
            if (Object.hasOwnProperty.call(questionsValue[key], k)) {
                const element = questionsValue[key][k];
                if(element.id == question.id){
                    return false
                }
            }
        }

        var grade = $('[name="grade-'+key+'"]').val()
        questionsList[key].push(question)
        questionsValue[key].push({
            id:question.id,
            grade:grade
        })

        createBtnFun.updateQuestion()
        var ind = $('.questionslist-box .question-list').length + 1
        var html = createBtnFun.addOneNewQuestionList(question,grade,ind)
        $('.questionslist-box .box-body').append(html)

    }

    // 一键生成按钮
    $('.create-auto-btn').click(function(){
       var course_id = createBtnFun.course_id()
       if(course_id == ''){
        layer.msg('请先选择课程')
        return false;
       }

        //弹出填写数量的窗口

        createBtnFun.createAutoFormIndex = layer.open({
            type: 1,//1 dom或文本，2 iframe,3 加载层,4 tips
            shadeClose:true,
            title:'填写数量',
            area: ['350px', '380px'],
            content: $('#create-auto-form') ,
            success: function(layero){
               
            }
        });

    })

    // 点击生成按钮时执行
    $('.create-auto').click(function (e) { 
        e.preventDefault();
        console.log('点击了');
        var formData = createBtnFun.getCreateFormData()
        $.ajax({
            type: "post",
            url: "./testpaper/createQuestionsAuto",
            data: formData,
            dataType: "json",
            success: function (response) {
                // console.log('response: ', response);
                layer.close(createBtnFun.createAutoFormIndex)
                questionsList = response.data 

                // questionsValue
                for (const key in questionsList) {
                    if (Object.hasOwnProperty.call(questionsList, key)) {
                        const element = questionsList[key];
                        
                        var grade = $('[name="grade-'+ key +'"]').val()
                        // console.log('grade: ', grade,key);

                        var value = []
                        for (const k in element) {
                            if (Object.hasOwnProperty.call(element, k)) {
                                const v = element[k];
                                value.push({
                                    id:v.id,
                                    grade:grade
                                })
                            }
                        }

                        questionsValue[key] = value
                    }
                }
                console.log('questionsValue: ', questionsValue);

                
                createBtnFun.updateQuestion()
            }
        });
    });
    
    // 当前选中的题目类型
    var selectedQuestionType
    // 点击题目数量,弹出窗口
    $('.questions-box').on('click','span',function(){
        console.log('点击了',$(this).index());
        var index = $(this).index()
        var key = 'type'+(index+1)
        console.log('key: ', key);
        selectedQuestionType = key

        layer.open({
          type: 1,//1 dom或文本，2 iframe,3 加载层,4 tips
          shadeClose:true,
          title:'题目列表',
          area: ['500px', '300px'],
          content: '<div class="questionslist-box"><div class="box-body"></div><div class="box-foot"><button type="button" class="btn btn-primary btn-add-question">添加题目</button></div></div>',
          success: function(layero){
              console.log('questionsList[key]: ', questionsList[key]);
              if(typeof questionsList[key] == 'undefined'){
                questionsList[key] = []
              }
              if(typeof questionsValue[key] == 'undefined'){
                questionsValue[key] = []
              }

              var listArray = questionsList[key]
              
              var htmls = []
              listArray.forEach((row,index) => {
                // console.log('row: ', row);
                var qv = questionsValue[key][index]
                // {id:xx,grade:xxx}
                htmls.push(createBtnFun.addOneNewQuestionList(row,qv.grade,index+1))
              });

              $('.questionslist-box .box-body').html(htmls.join(''))
           }
        });
    })

    // 剔除题目
    $(document).on('click','.remove-question',function(){
        var listBox = $(this).parent().parent()
        var index = listBox.index()
        listBox.remove()
        questionsList[selectedQuestionType].splice(index,1)
        questionsValue[selectedQuestionType].splice(index,1)

        // 重新执行计算
        createBtnFun.updateQuestion()
    })

    // 改变分数
    $(document).on('change','.question-list .grades',function(){
        var listBox = $(this).parent().parent()
        var index = listBox.index()
        var v = $(this).val()
        // console.log(questionsValue[selectedQuestionType][index],v);
        questionsValue[selectedQuestionType][index].grade = v

        // 修改总分，写入输入框
        createBtnFun.updateQuestionValue()
    })

    // 点击“添加题目”按钮
    $(document).on('click','.btn-add-question',function(){
        var type = selectedQuestionType.slice(4)
        createBtnFun.openChooseQuestionWindow(type)
    })

    $(document).on('click','.choose-type button',function(){
        var index = $(this).index()
        var type = index+1
        layer.close(createBtnFun.createBtnFormIndex)
        createBtnFun.openChooseQuestionWindow(type)
    })

    // 手动添加按钮
    $('.create-btn').click(function(){
        var course_id = createBtnFun.course_id()
        if(course_id == ''){
         layer.msg('请先选择课程')
         return false;
        }
        
        var arr = []
        for (const key in createBtnFun.questionTypeObj) {
            if (Object.hasOwnProperty.call(createBtnFun.questionTypeObj, key)) {
                const element = createBtnFun.questionTypeObj[key];
                arr.push(' <button type="button" class="btn btn-primary">'+element+'</button>')
            }
        }
        createBtnFun.createBtnFormIndex = layer.open({
          type: 1,//1 dom或文本，2 iframe,3 加载层,4 tips
          shadeClose:true,
          title:false,
          area: ['390px'],
          content: `
          <div class="choose-type" style="padding:20px;">
                ${arr.join('')}
          </div>
          ` ,
          success: function(layero){
               
           }
        });
 
     })

    var Controller = {
        index: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'testpaper/index' + location.search,
                    add_url: 'testpaper/add',
                    edit_url: 'testpaper/edit',
                    del_url: 'testpaper/del',
                    multi_url: 'testpaper/multi',
                    import_url: 'testpaper/import',
                    table: 'testpaper',
                }
            });

            var table = $("#table");

            // var arr = Config.testlist
            // var obj = arr.reduce((acc,cur,index)=>{
            //     acc[index] = cur
            //     return acc
            // },{})
            
            
        
            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'id',
                fixedColumns: true,
                fixedRightNumber: 1,
                search: false, //是否启用快速搜索
                
                searchFormVisible: true, //是否始终显示搜索表单
                columns: [
                    [
                        {checkbox: true},
                        {field: 'id', title: __('Id'),operate:false},
                        // {field: 'course_id', title: __('Course_id')},
                        {field: 'course.name', title: __('Course.name'), operate: 'LIKE'},
                        {field: 'title', title: __('Title'), operate: 'LIKE'},
                        {field: 'diffdata', title: __('Diffdata'), searchList: {"0":__('Diffdata 0'),"1":__('Diffdata 1'),"2":__('Diffdata 2'),"3":__('Diffdata 3'),"4":__('Diffdata 4'),"5":__('Diffdata 5')}, formatter: Table.api.formatter.normal},
                        {field: 'grades', title: __('Grades'), operate:'BETWEEN'},
                        
                        {field: 'status', title: __('Status'), searchList: {"1":__('Status 1'),"2":__('Status 2'),"3":__('Status 3')},custom:{1:'primary',2:'danger',3:'success'}, formatter: function(value, row, index){
                            // console.log('row: ', row);
                            var h = Table.api.formatter.status.call(this,value, row, index)
                            if(Config.can_change_status){
                                h+=' <button class="btn btn-xs btn-success btn-status-pass" data-id="'+row.id+'">通过</button> <button class="btn btn-xs btn-danger btn-status-reject" data-id="'+row.id+'">拒绝</button>'
                            }
                            return h
                        }},
                        {field: 'remark', title: __('Remark'), operate: 'LIKE', table: table, class: 'autocontent', formatter: function(v){
                            return !v?' - ':v;
                        }},
                       
                        {field: 'admin_id', title: __('Admin_id'),visible:false},
                       
                        {field: 'admin.username', title: __('Admin.username'), operate: 'LIKE'},
                        {field: 'createtime', title: __('Createtime'), operate:'RANGE', addclass:'datetimerange', autocomplete:false, formatter: Table.api.formatter.datetime},
                        {field: 'updatetime', title: __('Updatetime'), operate:'RANGE', addclass:'datetimerange', autocomplete:false, formatter: Table.api.formatter.datetime},
                        {field: 'operate', title: __('Operate'),align:'right', table: table, events: Table.api.events.operate, formatter: Table.api.formatter.operate,buttons:[
                            {
                                name:'qlist',
                                title:'题目列表',
                                classname:'btn btn-xs btn-primary btn-click',
                                icon:'fa fa-list-ul',
                                extend:'data-toggle="tooltip"',
                                visible:function(row){
                                    var qlists = JSON.parse(row.questions)
                                    console.log('qlists: ', qlists);
                                    for (const key in qlists) {
                                        if (Object.hasOwnProperty.call(qlists, key)) {
                                            const list = qlists[key];
                                            
                                            if(list.length>0){
                                                return true
                                            }
                                        }
                                    }

                                    return false
                                },
                                click:function(a,row,c){
                                    var qlists = JSON.parse(row.questions)
                                    console.log('qlists: ', qlists);

                                    var ids = {}

                                    for (const key in qlists) {
                                        if (Object.hasOwnProperty.call(qlists, key)) {
                                            const list = qlists[key];
                                            
                                            ids[key] = list.map(data=>data.id)
                                        }
                                    }
                                    console.log('ids: ', ids);

                                    $.ajax({
                                        type: "post",
                                        url: "./questions/getlist_by_ids",
                                        data: {
                                            ids:ids
                                        },
                                        dataType: "json",
                                        success: function (response) {
                                            console.log('response: ', response);
                                            
                                            if(response.code == 1){

                                                layer.open({
                                                    type: 1,//1 dom或文本，2 iframe,3 加载层,4 tips
                                                    shadeClose:true,
                                                    title:'题目列表',
                                                    area: ['800px', '600px'],
                                                    content: '<div class="questionslist-box"><div class="box-body"></div><div class="box-foot"></div></div>',
                                                    success: function(layero){
                                                        var lists = response.data
                                                        console.log('lists: ', lists);
                                                        var bigHtmls=[]
                                                        for (const key in lists) {
                                                            if (Object.hasOwnProperty.call(lists, key)) {
                                                                
                                                                var listArray = lists[key]
                                                        
                                                                var htmls = []
                                                                listArray.forEach((row,index) => {
                                                                  // console.log('row: ', row);
                                                                  htmls.push(createBtnFun.addOneNewQuestionList(row,false,index+1))
                                                                });

                                                                // 
                                                                var type = key.slice(4)
                                                                var title = '<div class="big-title">'+createBtnFun.questionTypeObj[type]+'</div>'
                                                                var str = title + htmls.join('')
                                                                bigHtmls.push(str)

                                                            }
                                                        }
                                                        // if(typeof questionsList[key] == 'undefined'){
                                                        //   questionsList[key] = []
                                                        // }
                                                        // if(typeof questionsValue[key] == 'undefined'){
                                                        //   questionsValue[key] = []
                                                        // }
                                          
                                                       
                                          
                                                        $('.questionslist-box .box-body').html(bigHtmls.join(''))
                                                     }
                                                  });
                                            }

                                        }
                                    });
                                }
                            }
                        ]}
                    ]
                ]
            });

            
            // 审核
            var audit = {
                pass:function(id){
                    $.ajax({
                        type: "post",
                        url: "./testpaper/change_status/type/pass",
                        data: {
                            id:id
                        },
                        dataType: "json",
                        success: function (response) {
                            console.log('response: ', response);
                            if(response.code == 1){
    
                                table.bootstrapTable('refresh')
                            }
                            else{
                                layer.msg(response.msg)
                            }
                        }
                    });
                },
                reject:function(id){
                    layer.prompt({title: '请输入拒绝原因', formType: 2}, function(val, index){
                        // 
                        if(val.trim()!==''){
      
                          $.ajax({
                              type: "post",
                              url: "./testpaper/change_status/type/reject",
                              data: {
                                  id:id,
                                  remark:val.trim()
                              },
                              dataType: "json",
                              success: function (response) {
                                  console.log('response: ', response);
                                  
                                  if(response.code == 1){
                                      layer.close(index);
                                      table.bootstrapTable('refresh')
                                  }
                                  else{
                                      layer.msg(response.msg)
                                  }
                              }
                          });
                        }
      
                      });
                }
            }
            // 批量通过
            $('.btn-audit-pass').click(function (e) { 
                e.preventDefault();
                var ids = Table.api.selectedids(table)
                audit.pass(ids)
            })

            // 批量拒绝
            $('.btn-audit-reject').click(function (e) { 
                e.preventDefault();
                var ids = Table.api.selectedids(table)
                audit.reject(ids)
            })

            // 通过
            $(document).on('click','.btn-status-pass',function(){
                var id = $(this).data('id');
                console.log('通过id: ', id);
                audit.pass(id)
            })

            // 拒绝
            $(document).on('click','.btn-status-reject',function(){
                var id = $(this).data('id');
                console.log('拒绝id: ', id);
                audit.reject(id)
            })

            // 为表格绑定事件
            Table.api.bindevent(table);
        },
        recyclebin: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    'dragsort_url': ''
                }
            });

            var table = $("#table");

            // 初始化表格
            table.bootstrapTable({
                url: 'testpaper/recyclebin' + location.search,
                pk: 'id',
                sortName: 'id',
                columns: [
                    [
                        {checkbox: true},
                        {field: 'id', title: __('Id')},
                        {field: 'title', title: __('Title'), align: 'left'},
                        {
                            field: 'deletetime',
                            title: __('Deletetime'),
                            operate: 'RANGE',
                            addclass: 'datetimerange',
                            formatter: Table.api.formatter.datetime
                        },
                        {
                            field: 'operate',
                            width: '140px',
                            title: __('Operate'),
                            table: table,
                            events: Table.api.events.operate,
                            buttons: [
                                {
                                    name: 'Restore',
                                    text: __('Restore'),
                                    classname: 'btn btn-xs btn-info btn-ajax btn-restoreit',
                                    icon: 'fa fa-rotate-left',
                                    url: 'testpaper/restore',
                                    refresh: true
                                },
                                {
                                    name: 'Destroy',
                                    text: __('Destroy'),
                                    classname: 'btn btn-xs btn-danger btn-ajax btn-destroyit',
                                    icon: 'fa fa-times',
                                    url: 'testpaper/destroy',
                                    refresh: true
                                }
                            ],
                            formatter: Table.api.formatter.operate
                        }
                    ]
                ]
            });

            // 为表格绑定事件
            Table.api.bindevent(table);
        },

        add: function () {
            Controller.api.bindevent();
        },
        edit: function () {
            Controller.api.bindevent();

            questionsValue = JSON.parse($('[name="row[questions]"]').val())
            questionsList = JSON.parse($('[name="row[questionslist]"]').val())
            // questionsList = 
            createBtnFun.updateQuestion()
        },
        api: {
            bindevent: function () {
                Form.api.bindevent($("form[role=form]"));
            }
        }
    };
    return Controller;
});
